package edu.cs335pl.questionnaire.config;

import edu.cs335pl.questionnaire.pojo.ServerResponse;
import edu.cs335pl.questionnaire.util.JWTutils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Objects;

@Slf4j
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setCharacterEncoding("utf-8");
        String token = request.getHeader("loginuser");
        log.info(token);
        if (token != null) {
            //!!!!!!!!!!!!!!!!!!!!!!!页面没写！！！！！！！！！！！！！！！！！！！！！
            //!!!!!!!!!!!!!!!!!!!!!!!页面没写！！！！！！！！！！！！！！！！！！！！！
            //!!!!!!!!!!!!!!!!!!!!!!!页面没写！！！！！！！！！！！！！！！！！！！！！
            //!!!!!!!!!!!!!!!!!!!!!!!页面没写！！！！！！！！！！！！！！！！！！！！！
            boolean result = JWTutils.verify(token);
            if (result) {
                return true;
            }
        }

        ServerResponse serverResponse = ServerResponse.ofError("Token认证失败");
        responseMessage(response, response.getWriter(), serverResponse);
        return false;
//        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private void responseMessage(HttpServletResponse response, PrintWriter out, ServerResponse serverResponse) {
        response.setContentType("application/json; charset=utf-8");
        out.print(JSONObject.toJSONString(serverResponse));
        out.flush();
        out.close();
    }

}
